package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.dto.RepairSheetOwnerIdDTO;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 逍邦网络科技有限公司<p>
 *
 * @author chenshan
 * @version v1.0
 * @since 2020-03-30 10:04
 */
@Controller
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/fund")
public class FundSheetOwnerIdController {
    private static final Logger LOG = LoggerFactory.getLogger(FundSheetOwnerIdController.class);
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    /**
     *
     * @param repairSheetOwnerIdDTO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/paymentSheet/ownerId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String paymentSheetOwnerId(@RequestBody @Valid RepairSheetOwnerIdDTO repairSheetOwnerIdDTO) throws Exception {
        try {
            if (!proBaseConfig.getXbbCode().equals(repairSheetOwnerIdDTO.getXbbCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
            }
            LOG.warn("-----------ownerId start 开始回款单的负责人处理-----------");
            List<String> corpidList = repairSheetOwnerIdDTO.getCorpidList();
            if ( CollectionsUtil.isEmpty(corpidList) ) {
                corpidList = companyModel.getCorpidList();
            }
            long timeStart = DateTimeUtil.getInt();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for ( String corpid : corpidList ) {
                Integer start = 0;
                //每次查询100条
                Integer pageNum = 1000;
                Long idGte = 0L;
                param.put("corpid",corpid);
                param.put("start", start);
                param.put("pageNum", pageNum);
                param.put("orderByStr", "id asc");
                param.put("del", 0);
                while (true) {
                    param.put("idGte", idGte);
                    LOG.warn("处理进度：已处理到 id = " + idGte);
                    List<PaymentSheetEntityExt> paymentSheetEntityExtList = paymentSheetModel.findEntitys(param);
                    if (paymentSheetEntityExtList == null || paymentSheetEntityExtList.size() == 0) {
                        break;
                    }
                    idGte = paymentSheetEntityExtList.get(paymentSheetEntityExtList.size() - 1).getId();
                    scriptPaymentSheet(corpid,XbbRefTypeEnum.PAYMENT_SHEET,paymentSheetEntityExtList);
                }
            }
            LOG.warn("-----------time consume:" + (DateTimeUtil.getInt() - timeStart));
            LOG.warn("-----------/script/fund/paymentSheet/ownerId over");
        } catch (Exception e) {
            LOG.error("/script/fund/paymentSheet/ownerId error", e);
        }
        LOG.warn("-----------处理完毕-----------");
        return JSON.toJSONString("{\"msg\":\"success\"}");
    }
    
    @RequestMapping(value = "/payPlanSheet/ownerId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String payPlanSheetOwnerId(@RequestBody @Valid RepairSheetOwnerIdDTO repairSheetOwnerIdDTO) throws Exception {
        try {
            if (!proBaseConfig.getXbbCode().equals(repairSheetOwnerIdDTO.getXbbCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
            }
            LOG.warn("-----------ownerId start 开始付款单的负责人处理-----------");
            List<String> corpidList = repairSheetOwnerIdDTO.getCorpidList();
            if ( CollectionsUtil.isEmpty(corpidList) ) {
                corpidList = companyModel.getCorpidList();
            }
            long timeStart = DateTimeUtil.getInt();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for ( String corpid : corpidList ) {
                Integer start = 0;
                //每次查询100条
                Integer pageNum = 1000;
                Long idGte = 0L;
                param.put("corpid",corpid);
                param.put("start", start);
                param.put("pageNum", pageNum);
                param.put("orderByStr", "id asc");
                param.put("del", 0);
                while (true) {
                    param.put("idGte", idGte);
                    LOG.warn("处理进度：已处理到 id = " + idGte);
                    List<PayPlanSheetEntityExt> payPlanSheetEntityExtList = payPlanSheetModel.findEntitys(param);
                    if (payPlanSheetEntityExtList == null || payPlanSheetEntityExtList.size() == 0) {
                        break;
                    }
                    idGte = payPlanSheetEntityExtList.get(payPlanSheetEntityExtList.size() - 1).getId();
                    scriptPayPlanSheet(corpid,XbbRefTypeEnum.PAY_SHEET,payPlanSheetEntityExtList);
                }
            }
            LOG.warn("-----------time consume:" + (DateTimeUtil.getInt() - timeStart));
            LOG.warn("-----------/script/fund/payPlanSheet/ownerId over");
        } catch (Exception e) {
            LOG.error("/script/fund/payPlanSheet/ownerId error", e);
        }
        LOG.warn("-----------处理完毕-----------");
        return JSON.toJSONString("{\"msg\":\"success\"}");
    }
    
    public void scriptPaymentSheet(String corpid, XbbRefTypeEnum businessTypeEnum,List<PaymentSheetEntityExt> paymentSheetEntityExtList) throws XbbException {
        List<PaasFormDataEntityExt> paasFormDataList = new ArrayList<>(paymentSheetEntityExtList.size());
        try {
            BeanUtil.copyPropertiesList(paymentSheetEntityExtList,paasFormDataList,PaasFormDataEntityExt.class);
        }catch (Exception e) {
            LOG.error("copyPropertiesList:paymentSheetEntityExtList错误",e);
        }
        userTeamService.scriptUserTeamBySheetBusiness(corpid,businessTypeEnum,paasFormDataList);
    }
    
    public void scriptPayPlanSheet(String corpid, XbbRefTypeEnum businessTypeEnum,List<PayPlanSheetEntityExt> payPlanSheetEntityExtList) throws XbbException {
        List<PaasFormDataEntityExt> paasFormDataList = new ArrayList<>(payPlanSheetEntityExtList.size());
        try {
            BeanUtil.copyPropertiesList(payPlanSheetEntityExtList,paasFormDataList,PaasFormDataEntityExt.class);
        }catch (Exception e) {
            LOG.error("copyPropertiesList:paymentSheetEntityExtList错误",e);
        }
        userTeamService.scriptUserTeamBySheetBusiness(corpid,businessTypeEnum,paasFormDataList);
    }
}
